﻿using AbstructFactory;
using ADManage.api.Common;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using XF.Meeting.Api.Models;
using XF.Meeting.Entity.com.chinadydc.sso;
using XF.Meeting.Entity.DTO;

namespace XF.Meeting.Api.sso
{
    public partial class ssoLogin : System.Web.UI.Page
    {
        private readonly string apiurl = UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["loginUrl"]));
        private readonly string secret = UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["secret"]));
        private readonly string ExpTime = UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ExpTime"]));
        private readonly string AppUrl = UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["AppUrl"]));
        private readonly string AppKey = UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["AppKey"]));
        private readonly string IdentityUrl = UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["IdentityUrl"]));
        public AbsFactoryTE abs = (AbsFactoryTE)AbsFactory.CreateInterface();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            
                string strCheckInfo = string.Empty;
                string tokenId = Post("TokenID");
                string key = Post("Key");
                do
                {
                    try
                    {
                        #region 接入SSO，获取用户信息
                        if (String.IsNullOrEmpty(tokenId))
                        {
                            NameValueCollection data = new NameValueCollection();
                            data.Add("AppUrl", AppUrl);
                            data.Add("AppKey", AppKey);
                            string strForm = PreparePOSTForm(IdentityUrl, data);
                            Page.Controls.Add(new LiteralControl(strForm));
                            break;
                        }
                        UnifiedIdentityService client = new UnifiedIdentityService();
                        string a = client.GetUserMsg(tokenId);
                        //UnifiedIdentityService.UnifiedIdentityService identityService = new UnifiedIdentityService.UnifiedIdentityService();
                        CInfo cinfo = (CInfo)Deserialize(typeof(CInfo), a);
                        if (cinfo.Result == "False")
                        {
                            strCheckInfo = cinfo.Error;
                            break;
                        }

                        UserLogin user = new UserLogin()
                        {
                            userName = cinfo.userInfo.ADAccount,
                            phone = cinfo.userInfo.MOBILE,

                        };
                        var service = abs.CreateUserInfoInterface(user.userName, IPHelper.GetIPAddress);

                        var result =  service.Login(user.userName).Result;
                        TokenInfo token1 = new TokenInfo();
                        if (result != null)
                        {

                            var jwtHelper = new JWTHelper();
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            dic.Add("userName", result.Account);
                            dic.Add("Name", result.AccountName);
                            dic.Add("IsAdmin", result.IsAdmin);
                            dic.Add("UserId", result.userId);
                            dic.Add("role", result.IsAdmin == 3 ? "Admin" : "User");
                            dic.Add("RegionalId", result.RegionalID);
                            dic.Add("RegionName", result.RegionalName);
                            dic.Add("email", result.email);
                            dic.Add("OrgId", result.OrgId);
                            dic.Add("wxType", result.wxType);
                            var token = jwtHelper.Encode(dic, secret, Convert.ToInt32(ExpTime));
                            Response.Redirect(apiurl + $"?token={token}", true);
                        }
                        else {
                            //Response.Write("<script>alert('认证失败：无此用户，请联系管理员添加');window.history.go(-1);</script>");
                            //Response.End();
                          
                        }
                        //string strsAMAccount = cinfo.userInfo.ADAccount;
                        //string strAccountName = cinfo.userInfo.NAME;
                        #endregion


                    }
                    catch (Exception ex)
                    {
                        strCheckInfo = string.Format(ex.Message);
                    }


                } while (false);

                if (!String.IsNullOrEmpty(strCheckInfo))
                {
                    strCheckInfo = HttpUtility.UrlEncode(strCheckInfo, Encoding.UTF8);
                    Response.Write(string.Format(@"<script>alert('登陆失败：{0}')</script>", strCheckInfo));
                }
            }
            //  string strOpreateIP = Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP. 

        }
        private string Post(string name)
        {
            string str = Request.Form[name];
            if (str != null)
            {
                return str.Trim();
            }
            return string.Empty;
        }
        private static String PreparePOSTForm(string url, NameValueCollection data)
        {
            //Set a name for the form
            string formID = "PostForm";

            //Build the form using the specified data to be posted.
            StringBuilder strForm = new StringBuilder();
            strForm.Append("<form id=\"" + formID + "\" name=\"" + formID + "\" action=\"" + url + "\" method=\"POST\">");
            //<form id="PostForm" name="PostForm" action="http://10.100.100.149/UnifiedSertificationWebService/IdentityCheck.aspx" method="POST">
            //<input type="hidden" name="AppUrl" value=" http://10.100.100.170/idpbipt/#/ ">
            //<input type="hidden" name="AppKey" value="6B6F3BD4-0798-440E-B9D9-34A119CE9B96 ">
            //</form>
            //<script language='javascript'>
            //var vPostForm=document.vPostForm
            //vPostForm.submit();
            //</script>
            foreach (string key in data)
            {
                strForm.Append("<input type=\"hidden\" name=\"" + key + "\" value=\"" + data[key] + "\">");
            }
            strForm.Append("</form>");

            //Build the JavaScript which will do the Posting operation.
            StringBuilder strScript = new StringBuilder();
            strScript.Append("<script language='javascript'>");
            strScript.Append("var v" + formID + " = document." + formID + ";");
            strScript.Append("v" + formID + ".submit();");
            strScript.Append("</script>");

            //Return the form and the script concatenated. (The order is important, Form then JavaScript)
            return strForm.ToString() + strScript.ToString();
        }

        public static object Deserialize(Type type, string xml)
        {
            using (StringReader sr = new StringReader(xml))
            {
                XmlSerializer xmldes = new XmlSerializer(type);
                return xmldes.Deserialize(sr);
            }
        }
    }
}